function rrdFetch(fname, cb) {
	try {
	  FetchBinaryURLAsync(fname, function(bf) {
		  var i_rrd_data=undefined;
		  try {
			var i_rrd_data=new RRDFile(bf);            
		  } catch(err) {
			cb(err);
		  }
		  if (i_rrd_data!=undefined) {
			cb(null, i_rrd_data);
		  }
	  });
	} catch (err) {
	  cb(err);
	}
}
var flot = null;
function draw_chart(divid, rrddata) {
	if ((rrddata==undefined)) {
	  return; /* some data still missing */
	}
    rrd_data_sum=new RRDFileSum([rrddata]);
       
	// the rrdFlot object creates and handles the graph
	//var rrdflot_defaults={graph_only:false,use_checked_DSs:true,checked_DSs:['outdoor'],use_rra:true,rra:0,}
	var rrdflot_defaults={ 
		graph_width:"700px", graph_height:"300px", 
		scale_width:"450px", scale_height:"100px", 
		//timezone:"+2",
		//use_elem_buttons: true,
		//use_rra: true,
		//multi_rra: true	
	};
	var graph_opts= {
		legend: { noColumns:4},
		tooltip: true,
		tooltipOpts: { content: "<h4>%s</h4> %x <br>Value: %y.3" }
	};
	var ds_graph_opts={ 
        'W':{ 
            //color: "#ff8000", 
            label: 'energy [W]',
            lines: { show: true, fill: false, fillColor:"#ffff80"},
            //checked: flot?flot.ds_graph_options.outdoor.checked:true
        },
       'kWh':{ 
            label: 'energy [kWh]', color: "#00c0c0", 
            lines: { show: true, fill: false},
            //checked: flot?flot.ds_graph_options.livingroom.checked:true
        }
    };

	// the rrdFlot object creates and handles the graph
	flot=new rrdFlot(divid,rrd_data_sum,graph_opts,ds_graph_opts, rrdflot_defaults);
}
$(function() {
     $.getJSON("/devices.json", function(data){
        $.each(data.rows, function(key, val)
        {
            if( val.doc.type == "meter" )
            {
                if( val.doc.meter.rrd.href )
                {
                    rrdFetch(val.doc.meter.rrd.href, function(error, data){
                        if(error){
                            //alert("File "+fname+" is not a valid RRD archive!\n"+err);
                        } else {
                            $("#charts").html("RRDfetch success!");
                            draw_chart("charts", data);
                        }
                        
                    });
                }
            }
        });
    });
     
});